package com.controller;

import com.alibaba.fastjson.JSON;
import com.pojo.Vo.SysUserVo;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController {
    @Autowired
    UserService userService;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 跳转到登录页
     * @return
     */
    @RequestMapping("/")
    public Object login(){
        return "login";
    }

    /**
     * 登录验证
     * @param usrName  用户名
     * @param usrPassword  密码
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/doLogin")
    public Object list(String usrName, String usrPassword,boolean remeberMe,Model model, HttpSession session){
        SysUserVo user= userService.login(usrName, usrPassword);
        if (user==null){
            model.addAttribute("message","账号或密码错误");
            return "login";
        }else {
            if (remeberMe){
                stringRedisTemplate.opsForValue().set("loginUser", JSON.toJSONString(user));
            }
            session.setAttribute("loginUser", user);
            return "main";
        }
    }

    /**
     * 退出
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public Object logout(HttpSession session){
        session.removeAttribute("loginUser");
        return "login";
    }
}
